// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.AdjustmentOrderProduct;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.AdjustmentOrderProductMapper;
import com.fowo.api.mapper.InventoryPlacementRMapper;
import com.fowo.api.mapper.ListingFatherMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.WarehouseBinMapper;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductExcelPo;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductImportPo;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductItemVo;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductItemVoPages;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductSearchParamPo;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductVo;
import com.fowo.api.model.inventory.placement.r.InventoryPlacementRItemVo;
import com.fowo.api.model.inventory.placement.r.InventoryPlacementRSearchParamPo;
import com.fowo.api.model.listing.father.ListingFatherItemVo;
import com.fowo.api.model.listing.father.ListingFatherSearchParamPo;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.warehouse.bin.WarehouseBinItemVo;
import com.fowo.api.model.warehouse.bin.WarehouseBinSearchParamPo;
import com.fowo.api.service.AdjustmentOrderProductService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 调整单子表 服务实现类
 * @author 蜂窝蜜造平台 配置人：李玉娇，王阳阳
 */
@Service
@Slf4j
@DataObjectType(AdjustmentOrderProduct.class)
@DS("ds24")
public class AdjustmentOrderProductServiceImpl
  extends ServiceImpl<AdjustmentOrderProductMapper, AdjustmentOrderProduct>
  implements AdjustmentOrderProductService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("parentAdjustmentOrderOrderSn", "ao.`order_sn`");
      put("prdNameName", "p.`name`");
      put("shopShopName", "si.`shop_name`");
      put("newPrdNameName", "p2.`name`");
      put("newShopShopName", "si2.`shop_name`");
      put("newFnskuFnsku", "lf.`fnsku`");
      put("goodWarehouseBinStorageBin", "wb.`storage_bin`");
      put("badWarehouseBinStorageBin", "wb2.`storage_bin`");
      put("newGoodWhbStorageBin", "wb3.`storage_bin`");
      put("newBadWhbStorageBin", "wb4.`storage_bin`");
      put("inventoryIdId", "ipr.`id`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected AdjustmentOrderProductService self;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected ListingFatherMapper listingFatherMapper;

  @Resource
  protected WarehouseBinMapper warehouseBinMapper;

  @Resource
  protected InventoryPlacementRMapper inventoryPlacementRMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建调整单子表
   * @param model 调整单子表
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(AdjustmentOrderProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AdjustmentOrderProduct entity = new AdjustmentOrderProduct();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("调整单子表保存失败");
  }

  /**
   * 批量更新 调整单 下属数据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void saveAllByParentAdjustmentOrder(
    Long parentAdjustmentOrder,
    List<AdjustmentOrderProductItemVo> list
  ) throws Exception {
    for (AdjustmentOrderProductItemVo itemVo : list) {
      if (
        itemVo.getId() != null &&
        itemVo.getDelFlag() != null &&
        itemVo.getDelFlag()
      ) {
        // 删除处理
        this.delete(itemVo.getId());
        continue;
      }
      AdjustmentOrderProduct item = new AdjustmentOrderProduct();
      BeanUtils.copyProperties(itemVo, item);
      if (item.getParentAdjustmentOrder() == null) {
        item.setId(null);
        item.setParentAdjustmentOrder(parentAdjustmentOrder);
      }
      if (item.getId() == null) {
        this.save(item);
      } else {
        this.updateById(item);
      }
    }
  }

  /**
   * 返回 调整单 下属多级分页
   */
  @Override
  public Map<String, Page<AdjustmentOrderProductItemVoPages>> pagesByParentAdjustmentOrder(
    AdjustmentOrderProductSearchParamPo search
  ) {
    search.setDisableDataPremissions(true);
    List<AdjustmentOrderProductItemVoPages> listMap =
      baseMapper.selectPagesByParentAdjustmentOrder(search);
    Map<Long, List<AdjustmentOrderProductItemVoPages>> pageMap = listMap
      .stream()
      .collect(
        Collectors.groupingBy(
          AdjustmentOrderProductItemVoPages::getParentAdjustmentOrder
        )
      );
    Map<String, Page<AdjustmentOrderProductItemVoPages>> result =
      new HashMap<>();
    for (Map.Entry<Long, List<AdjustmentOrderProductItemVoPages>> listEntry : pageMap.entrySet()) {
      Page<AdjustmentOrderProductItemVoPages> page = new Page<>(
        1,
        search.getPageSize(),
        listEntry.getValue().get(0).getPartRows()
      );
      page.setRecords(listEntry.getValue());
      result.put(listEntry.getKey().toString(), page);
    }
    return result;
  }

  /**
   * 更新调整单子表
   * @param model 调整单子表
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(AdjustmentOrderProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AdjustmentOrderProduct entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("调整单子表不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "picUrl",
      "prdName",
      "sku",
      "prdLabel",
      "shop",
      "fnsku",
      "availbleNum",
      "newAvailbleNum",
      "defectiveQuantity",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "goodWarehouseBin",
      "badWarehouseBin"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新调整单子表（带空值）
   * @param model 调整单子表
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(AdjustmentOrderProductVo model)
    throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AdjustmentOrderProduct entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("调整单子表不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(
        AdjustmentOrderProduct::getParentAdjustmentOrder,
        model.getParentAdjustmentOrder()
      )
      .set(AdjustmentOrderProduct::getNewPrdName, model.getNewPrdName())
      .set(AdjustmentOrderProduct::getNewSku, model.getNewSku())
      .set(AdjustmentOrderProduct::getNewShop, model.getNewShop())
      .set(AdjustmentOrderProduct::getNewFnsku, model.getNewFnsku())
      .set(AdjustmentOrderProduct::getGoodAdjustNum, model.getGoodAdjustNum())
      .set(AdjustmentOrderProduct::getBadAdjustNum, model.getBadAdjustNum())
      .set(
        AdjustmentOrderProduct::getAdjustmentAmount,
        model.getAdjustmentAmount()
      )
      .set(AdjustmentOrderProduct::getLastUpdateTime, model.getLastUpdateTime())
      .set(AdjustmentOrderProduct::getLastUpdateUser, model.getLastUpdateUser())
      .set(AdjustmentOrderProduct::getNewGoodWhb, model.getNewGoodWhb())
      .set(AdjustmentOrderProduct::getNewBadWhb, model.getNewBadWhb())
      .set(AdjustmentOrderProduct::getRemark, model.getRemark())
      .set(AdjustmentOrderProduct::getInventoryId, model.getInventoryId())
      .set(AdjustmentOrderProduct::getFnskuName, model.getFnskuName())
      .set(AdjustmentOrderProduct::getNewFnskuName, model.getNewFnskuName())
      .eq(AdjustmentOrderProduct::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    AdjustmentOrderProductSearchParamPo search
  ) {
    return false;
  }

  /**
   * 删除调整单子表
   * @param id 调整单子表的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除调整单子表
   * @param ids 调整单子表的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<AdjustmentOrderProductImportPo> excelToImportRow(
    AdjustmentOrderProductImportPo row,
    Integer rowNumber,
    AdjustmentOrderProductVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<AdjustmentOrderProductImportPo> ir =
      new ImportRow<AdjustmentOrderProductImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<AdjustmentOrderProductImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new AdjustmentOrderProductVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, AdjustmentOrderProductImportPo.class);

    // 一般数据处理
    vo.setAvailbleNum(SheetUtils.tryToLong(row.getAvailbleNum()));
    vo.setNewAvailbleNum(SheetUtils.tryToLong(row.getNewAvailbleNum()));
    vo.setGoodAdjustNum(SheetUtils.tryToLong(row.getGoodAdjustNum()));
    vo.setDefectiveQuantity(SheetUtils.tryToLong(row.getDefectiveQuantity()));
    vo.setBadAdjustNum(SheetUtils.tryToLong(row.getBadAdjustNum()));
    vo.setAdjustmentAmount(SheetUtils.tryToLong(row.getAdjustmentAmount()));
    // 处理关联字段“品名”
    if (
      !SheetUtils.isBlank(row.getPrdNameName()) &&
      SheetUtils.isBlank(row.getPrdName())
    ) {
      ProductSearchParamPo prdNameSearchParam = new ProductSearchParamPo();
      prdNameSearchParam.setLimit(2); // 最大只返回二行记录
      prdNameSearchParam.setNameEq(SheetUtils.trim(row.getPrdNameName()));
      prdNameSearchParam.applySqlSegments();
      List<ProductItemVo> prdNameMatches = productMapper.search(
        prdNameSearchParam
      );
      if (prdNameMatches.size() == 0) {
        ir.addError("prdNameName", "未能在产品管理中找到匹配的数据");
      } else if (prdNameMatches.size() > 1) {
        ir.addError(
          "prdNameName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setPrdName(prdNameMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", prdNameMatches.get(0).getId())
          .put("fromObjectName", "AdjustmentOrderProduct")
          .put("fromObjectId", vo.getId())
          .put("fromField", "prdName")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(2);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("sku")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("sku")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("sku")
              .rowFieldName("sku")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("prdLabel")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("label")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("prdLabel")
              .rowFieldName("prdLabel")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(prdNameMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopShopName()) &&
      SheetUtils.isBlank(row.getShop())
    ) {
      ShopInfoSearchParamPo shopSearchParam = new ShopInfoSearchParamPo();
      shopSearchParam.setLimit(2); // 最大只返回二行记录
      shopSearchParam.setShopNameEq(SheetUtils.trim(row.getShopShopName()));
      shopSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopMatches = shopInfoMapper.search(shopSearchParam);
      if (shopMatches.size() == 0) {
        ir.addError("shopShopName", "未能在店铺中找到匹配的数据");
      } else if (shopMatches.size() > 1) {
        ir.addError("shopShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setShop(shopMatches.get(0).getId());
      }
    }
    // 处理关联字段“FNSKU”
    if (
      !SheetUtils.isBlank(row.getFnskuFnsku()) &&
      SheetUtils.isBlank(row.getFnsku())
    ) {
      ListingFatherSearchParamPo fnskuSearchParam =
        new ListingFatherSearchParamPo();
      fnskuSearchParam.setLimit(2); // 最大只返回二行记录
      fnskuSearchParam.setFnskuEq(SheetUtils.trim(row.getFnskuFnsku()));
      fnskuSearchParam.applySqlSegments();
      List<ListingFatherItemVo> fnskuMatches = listingFatherMapper.search(
        fnskuSearchParam
      );
      if (fnskuMatches.size() == 0) {
        ir.addError("fnskuFnsku", "未能在Listing中找到匹配的数据");
      } else if (fnskuMatches.size() > 1) {
        ir.addError("fnskuFnsku", "关联不唯一，在Listing中找到多个匹配的数据");
      } else {
        vo.setFnsku(fnskuMatches.get(0).getId());
      }
    }
    // 处理关联字段“新品名”
    if (
      !SheetUtils.isBlank(row.getNewPrdNameName()) &&
      SheetUtils.isBlank(row.getNewPrdName())
    ) {
      ProductSearchParamPo newPrdNameSearchParam = new ProductSearchParamPo();
      newPrdNameSearchParam.setLimit(2); // 最大只返回二行记录
      newPrdNameSearchParam.setNameEq(SheetUtils.trim(row.getNewPrdNameName()));
      newPrdNameSearchParam.applySqlSegments();
      List<ProductItemVo> newPrdNameMatches = productMapper.search(
        newPrdNameSearchParam
      );
      if (newPrdNameMatches.size() == 0) {
        ir.addError("newPrdNameName", "未能在产品管理中找到匹配的数据");
      } else if (newPrdNameMatches.size() > 1) {
        ir.addError(
          "newPrdNameName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setNewPrdName(newPrdNameMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", newPrdNameMatches.get(0).getId())
          .put("fromObjectName", "AdjustmentOrderProduct")
          .put("fromObjectId", vo.getId())
          .put("fromField", "newPrdName")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(1);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("newSku")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("sku")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("newSku")
              .rowFieldName("newSku")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(newPrdNameMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“新店铺”
    if (
      !SheetUtils.isBlank(row.getNewShopShopName()) &&
      SheetUtils.isBlank(row.getNewShop())
    ) {
      ShopInfoSearchParamPo newShopSearchParam = new ShopInfoSearchParamPo();
      newShopSearchParam.setLimit(2); // 最大只返回二行记录
      newShopSearchParam.setShopNameEq(
        SheetUtils.trim(row.getNewShopShopName())
      );
      newShopSearchParam.applySqlSegments();
      List<ShopInfoItemVo> newShopMatches = shopInfoMapper.search(
        newShopSearchParam
      );
      if (newShopMatches.size() == 0) {
        ir.addError("newShopShopName", "未能在店铺中找到匹配的数据");
      } else if (newShopMatches.size() > 1) {
        ir.addError(
          "newShopShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setNewShop(newShopMatches.get(0).getId());
      }
    }
    // 处理关联字段“新FNSKU”
    if (
      !SheetUtils.isBlank(row.getNewFnskuFnsku()) &&
      SheetUtils.isBlank(row.getNewFnsku())
    ) {
      ListingFatherSearchParamPo newFnskuSearchParam =
        new ListingFatherSearchParamPo();
      newFnskuSearchParam.setLimit(2); // 最大只返回二行记录
      newFnskuSearchParam.setFnskuEq(SheetUtils.trim(row.getNewFnskuFnsku()));
      newFnskuSearchParam.applySqlSegments();
      List<ListingFatherItemVo> newFnskuMatches = listingFatherMapper.search(
        newFnskuSearchParam
      );
      if (newFnskuMatches.size() == 0) {
        ir.addError("newFnskuFnsku", "未能在Listing中找到匹配的数据");
      } else if (newFnskuMatches.size() > 1) {
        ir.addError(
          "newFnskuFnsku",
          "关联不唯一，在Listing中找到多个匹配的数据"
        );
      } else {
        vo.setNewFnsku(newFnskuMatches.get(0).getId());
      }
    }
    // 处理关联字段“出库仓位”
    if (
      !SheetUtils.isBlank(row.getGoodWarehouseBinStorageBin()) &&
      SheetUtils.isBlank(row.getGoodWarehouseBin())
    ) {
      WarehouseBinSearchParamPo goodWarehouseBinSearchParam =
        new WarehouseBinSearchParamPo();
      goodWarehouseBinSearchParam.setLimit(2); // 最大只返回二行记录
      goodWarehouseBinSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getGoodWarehouseBinStorageBin())
      );
      goodWarehouseBinSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> goodWarehouseBinMatches =
        warehouseBinMapper.search(goodWarehouseBinSearchParam);
      if (goodWarehouseBinMatches.size() == 0) {
        ir.addError("goodWarehouseBinStorageBin", "未能在仓位中找到匹配的数据");
      } else if (goodWarehouseBinMatches.size() > 1) {
        ir.addError(
          "goodWarehouseBinStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setGoodWarehouseBin(goodWarehouseBinMatches.get(0).getId());
      }
    }
    // 处理关联字段“次品仓位”
    if (
      !SheetUtils.isBlank(row.getBadWarehouseBinStorageBin()) &&
      SheetUtils.isBlank(row.getBadWarehouseBin())
    ) {
      WarehouseBinSearchParamPo badWarehouseBinSearchParam =
        new WarehouseBinSearchParamPo();
      badWarehouseBinSearchParam.setLimit(2); // 最大只返回二行记录
      badWarehouseBinSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getBadWarehouseBinStorageBin())
      );
      badWarehouseBinSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> badWarehouseBinMatches =
        warehouseBinMapper.search(badWarehouseBinSearchParam);
      if (badWarehouseBinMatches.size() == 0) {
        ir.addError("badWarehouseBinStorageBin", "未能在仓位中找到匹配的数据");
      } else if (badWarehouseBinMatches.size() > 1) {
        ir.addError(
          "badWarehouseBinStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setBadWarehouseBin(badWarehouseBinMatches.get(0).getId());
      }
    }
    // 处理关联字段“入库仓位”
    if (
      !SheetUtils.isBlank(row.getNewGoodWhbStorageBin()) &&
      SheetUtils.isBlank(row.getNewGoodWhb())
    ) {
      WarehouseBinSearchParamPo newGoodWhbSearchParam =
        new WarehouseBinSearchParamPo();
      newGoodWhbSearchParam.setLimit(2); // 最大只返回二行记录
      newGoodWhbSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getNewGoodWhbStorageBin())
      );
      newGoodWhbSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> newGoodWhbMatches = warehouseBinMapper.search(
        newGoodWhbSearchParam
      );
      if (newGoodWhbMatches.size() == 0) {
        ir.addError("newGoodWhbStorageBin", "未能在仓位中找到匹配的数据");
      } else if (newGoodWhbMatches.size() > 1) {
        ir.addError(
          "newGoodWhbStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setNewGoodWhb(newGoodWhbMatches.get(0).getId());
      }
    }
    // 处理关联字段“新次品仓位”
    if (
      !SheetUtils.isBlank(row.getNewBadWhbStorageBin()) &&
      SheetUtils.isBlank(row.getNewBadWhb())
    ) {
      WarehouseBinSearchParamPo newBadWhbSearchParam =
        new WarehouseBinSearchParamPo();
      newBadWhbSearchParam.setLimit(2); // 最大只返回二行记录
      newBadWhbSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getNewBadWhbStorageBin())
      );
      newBadWhbSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> newBadWhbMatches = warehouseBinMapper.search(
        newBadWhbSearchParam
      );
      if (newBadWhbMatches.size() == 0) {
        ir.addError("newBadWhbStorageBin", "未能在仓位中找到匹配的数据");
      } else if (newBadWhbMatches.size() > 1) {
        ir.addError(
          "newBadWhbStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setNewBadWhb(newBadWhbMatches.get(0).getId());
      }
    }
    // 处理关联字段“库存”
    if (
      !SheetUtils.isBlank(row.getInventoryIdId()) &&
      SheetUtils.isBlank(row.getInventoryId())
    ) {
      InventoryPlacementRSearchParamPo inventoryIdSearchParam =
        new InventoryPlacementRSearchParamPo();
      inventoryIdSearchParam.setLimit(2); // 最大只返回二行记录
      inventoryIdSearchParam.setIdEq(SheetUtils.toLong(row.getInventoryIdId()));
      inventoryIdSearchParam.applySqlSegments();
      List<InventoryPlacementRItemVo> inventoryIdMatches =
        inventoryPlacementRMapper.search(inventoryIdSearchParam);
      if (inventoryIdMatches.size() == 0) {
        ir.addError("inventoryIdId", "未能在库存货位放置表中找到匹配的数据");
      } else if (inventoryIdMatches.size() > 1) {
        ir.addError(
          "inventoryIdId",
          "关联不唯一，在库存货位放置表中找到多个匹配的数据"
        );
      } else {
        vo.setInventoryId(inventoryIdMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<AdjustmentOrderProductImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<AdjustmentOrderProductImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            AdjustmentOrderProductImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              AdjustmentOrderProductImportPo row,
              AnalysisContext cxt
            ) {
              AdjustmentOrderProductVo vo = new AdjustmentOrderProductVo();
              ImportRow<AdjustmentOrderProductImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<AdjustmentOrderProductImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<AdjustmentOrderProductImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      AdjustmentOrderProductVo vo = new AdjustmentOrderProductVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    AdjustmentOrderProductSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "parentAdjustmentOrder",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              (
                (AdjustmentOrderProductItemVo) r
              ).getParentAdjustmentOrderOrderSn()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "prdName",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((AdjustmentOrderProductItemVo) r).getPrdNameName())
          )
      );
      exportOptions.addFieldMappingOption(
        "shop",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((AdjustmentOrderProductItemVo) r).getShopShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "fnsku",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((AdjustmentOrderProductItemVo) r).getFnskuFnsku())
          )
      );
      exportOptions.addFieldMappingOption(
        "newPrdName",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewPrdNameName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "newShop",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewShopShopName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "newFnsku",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewFnskuFnsku()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "goodWarehouseBin",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getGoodWarehouseBinStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "badWarehouseBin",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getBadWarehouseBinStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "newGoodWhb",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewGoodWhbStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "newBadWhb",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewBadWhbStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "inventoryId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getInventoryIdId()
            )
          )
      );
      exportOptions.addStringFields(
        "parentAdjustmentOrderOrderSn",
        "prdNameName",
        "sku",
        "prdLabel",
        "shopShopName",
        "fnskuFnsku",
        "newPrdNameName",
        "newSku",
        "newShopShopName",
        "newFnskuFnsku",
        "goodWarehouseBinStorageBin",
        "badWarehouseBinStorageBin",
        "newGoodWhbStorageBin",
        "newBadWhbStorageBin",
        "remark"
      );

      String fileName = String.format(
        "调整单子表(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<AdjustmentOrderProductExcelPo> items =
      new ArrayList<AdjustmentOrderProductExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<AdjustmentOrderProductItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<AdjustmentOrderProductItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (AdjustmentOrderProductItemVo item : list) {
        AdjustmentOrderProductExcelPo excel =
          new AdjustmentOrderProductExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "调整单子表(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(AdjustmentOrderProductExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过产品查询调整单子表主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByProduct(String product) {
    return this.baseMapper.getIdByProduct(product);
  }

  /**
   * 通过产品查询调整单子表多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByProduct(List<String> list) {
    return this.baseMapper.getIdsByProduct(list);
  }

  /**
   * 通过调整单子表主键查询产品
   */
  @Override
  public String getProductById(Long id) {
    return this.baseMapper.getProductById(id);
  }

  /**
   * 通过调整单子表主键查询产品列表
   */
  @Override
  public List<String> getProductByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getProductByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("product"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 调整单子表的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public AdjustmentOrderProductVo getVoById(Long id) throws Exception {
    AdjustmentOrderProductVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询调整单子表
   * @param search 查询条件
   * @return 调整单子表分页查询结果
   */
  @Override
  public Page<AdjustmentOrderProductItemVo> pageSearch(
    AdjustmentOrderProductSearchParamPo search
  ) {
    Page<AdjustmentOrderProductItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(AdjustmentOrderProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 调整单子表快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'AdjustmentOrderProductOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<AdjustmentOrderProductItemVo>> searchOptions(
    AdjustmentOrderProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询调整单子表
   * @param search 查询条件
   * @return 调整单子表列表查询结果
   */
  @Override
  public List<AdjustmentOrderProductItemVo> search(
    AdjustmentOrderProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询调整单子表最后更新时间
   * @param search 查询条件
   * @return 调整单子表最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(AdjustmentOrderProductSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
